﻿using System;
using System.IO;
using System.Reflection;
using System.Collections;

namespace Builderator.Core
{
    public class RemoteLoader : MarshalByRefObject
    {
        private ArrayList typeList, assemblyList;

        public RemoteLoader()
        {
            this.typeList = new ArrayList();

            this.assemblyList = new ArrayList();
        }

        public void LoadAssembly(string assemblyFullName)
        {
            string path, fileName;

            path = Path.GetDirectoryName(assemblyFullName);

            fileName = Path.GetFileNameWithoutExtension(assemblyFullName);

            Assembly assembly = Assembly.Load(fileName);

            this.assemblyList.Add(assembly);

            foreach (Type loadedType in assembly.GetTypes())
            {
                this.typeList.Add(loadedType);
            }
        }

        public string[] GetTypes()
        {
            ArrayList classList = new ArrayList();

            foreach (Type pluginType in this.typeList)
            {
                classList.Add(pluginType.FullName);
            }

            return (string[])classList.ToArray(typeof(string));
        }

        public string[] GetAssmeblies()
        {
            ArrayList assemblyNameList = new ArrayList();

            foreach (Assembly userAssembly in this.assemblyList)
            {
                assemblyNameList.Add(userAssembly.FullName);
            }

            return (string[])assemblyNameList.ToArray(typeof(string));
        }

        public object CreateInstance(string typeName)
        {
            Assembly owningAssembly = null;

            foreach (Assembly assembly in this.assemblyList)
            {
                if (assembly.GetType(typeName) != null)
                {
                    owningAssembly = assembly;

                    break;
                }
            }

            return owningAssembly.CreateInstance(typeName);
        }
    }
}